#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Imageset查看器模块
提供CEGUI布局编辑器的图像集查看功能
"""

import os
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QScrollArea, 
                           QLabel, QComboBox, QPushButton, QTreeWidget, QTreeWidgetItem,
                           QFileDialog)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QColor, QPen, QPixmap, QImage, QFont

class ImagesetViewer(QWidget):
    """Imageset查看器部件"""
    
    def __init__(self, xml_handler, parent=None):
        super(ImagesetViewer, self).__init__(parent)
        self.xml_handler = xml_handler
        self.current_imageset = None
        self.current_image = None
        self.init_ui()
    
    def init_ui(self):
        """初始化UI"""
        # 创建主布局
        layout = QVBoxLayout(self)
        
        # 创建顶部控件
        top_layout = QHBoxLayout()
        
        self.imageset_combo = QComboBox()
        self.imageset_combo.currentIndexChanged.connect(self.on_imageset_changed)
        top_layout.addWidget(QLabel('选择Imageset:'))
        top_layout.addWidget(self.imageset_combo)
        
        load_button = QPushButton('加载Imageset')
        load_button.clicked.connect(self.load_imageset)
        top_layout.addWidget(load_button)
        
        layout.addLayout(top_layout)
        
        # 创建图像列表
        self.image_list = QTreeWidget()
        self.image_list.setHeaderLabels(['图像名称', '位置', '大小', '偏移'])
        self.image_list.itemClicked.connect(self.on_image_clicked)
        layout.addWidget(self.image_list)
        
        # 创建预览区域
        preview_layout = QVBoxLayout()
        preview_layout.addWidget(QLabel('图像预览:'))
        
        self.preview_label = QLabel()
        self.preview_label.setAlignment(Qt.AlignCenter)
        self.preview_label.setMinimumSize(200, 200)
        self.preview_label.setStyleSheet("background-color: #444444; border: 1px solid #666666;")
        
        preview_layout.addWidget(self.preview_label)
        layout.addLayout(preview_layout)
    
    def load_imageset(self):
        """加载Imageset文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, 
            '加载Imageset文件', 
            '', 
            'Imageset文件 (*.imageset *.xml)'
        )
        if file_path:
            imageset = self.xml_handler.load_imageset(file_path)
            if imageset:
                self.statusBar().showMessage(f'已加载Imageset文件: {file_path}')
                self.update_imageset_combo()
    
    def update_imageset_combo(self):
        """更新Imageset下拉列表"""
        self.imageset_combo.clear()
        for name in sorted(self.xml_handler.imagesets.keys()):
            self.imageset_combo.addItem(name)
    
    def update_imageset_view(self, imageset):
        """更新Imageset视图"""
        self.update_imageset_combo()
        
        # 查找并选择加载的imageset
        index = self.imageset_combo.findText(self.xml_handler.current_imageset)
        if index >= 0:
            self.imageset_combo.setCurrentIndex(index)
    
    def on_imageset_changed(self, index):
        """Imageset选择变更"""
        if index < 0:
            return
        
        imageset_name = self.imageset_combo.currentText()
        if imageset_name in self.xml_handler.imagesets:
            self.current_imageset = imageset_name
            self.update_image_list()
    
    def update_image_list(self):
        """更新图像列表"""
        self.image_list.clear()
        
        if not self.current_imageset or self.current_imageset not in self.xml_handler.imagesets:
            return
        
        imageset = self.xml_handler.imagesets[self.current_imageset]
        
        for name, info in sorted(imageset['Images'].items()):
            item = QTreeWidgetItem(self.image_list)
            item.setText(0, name)
            item.setText(1, f"({info['XPos']}, {info['YPos']})")
            item.setText(2, f"{info['Width']} x {info['Height']}")
            item.setText(3, f"({info['XOffset']}, {info['YOffset']})")
            item.setData(0, Qt.UserRole, name)
    
    def on_image_clicked(self, item):
        """图像项被点击"""
        image_name = item.data(0, Qt.UserRole)
        if not image_name or not self.current_imageset:
            return
        
        # 获取图像信息
        img_info = self.xml_handler.get_image_info(self.current_imageset, image_name)
        if not img_info:
            return
            
        self.current_image = image_name
        self.update_image_preview()
    
    def update_image_preview(self):
        """更新图像预览"""
        if not self.current_imageset or not self.current_image:
            return
            
        img_info = self.xml_handler.get_image_info(self.current_imageset, self.current_image)
        if not img_info:
            return
            
        # 获取图像文件路径
        image_path = self.xml_handler.get_image_path(self.current_imageset)
        if not image_path or not os.path.isfile(image_path):
            # 如果找不到图像文件，显示占位符
            pixmap = QPixmap(200, 200)
            pixmap.fill(QColor(0, 0, 0, 0))
            
            painter = QPainter(pixmap)
            painter.fillRect(50, 50, 100, 100, QColor(0, 120, 200))
            painter.setPen(QColor(255, 255, 255))
            painter.drawText(50, 40, f"{self.current_imageset}:{self.current_image}")
            painter.drawText(50, 170, f"{img_info['Width']} x {img_info['Height']}")
            painter.end()
            
            self.preview_label.setPixmap(pixmap)
            
            # 添加图像信息到工具提示
            self.preview_label.setToolTip(
                f"名称: {self.current_image}\n"
                f"大小: {img_info['Width']} x {img_info['Height']}\n"
                f"位置: ({img_info['XPos']}, {img_info['YPos']})\n"
                f"偏移: ({img_info['XOffset']}, {img_info['YOffset']})"
            )
            return
        
        try:
            # 加载完整图像
            full_image = QImage(image_path)
            if full_image.isNull():
                raise Exception("无法加载图像文件")
                
            # 从完整图像中裁剪出当前图像
            sub_image = full_image.copy(
                img_info['XPos'], 
                img_info['YPos'], 
                img_info['Width'], 
                img_info['Height']
            )
            
            # 如果图像太大，调整显示尺寸
            pixmap = QPixmap.fromImage(sub_image)
            max_size = max(img_info['Width'], img_info['Height'])
            if max_size > 200:
                pixmap = pixmap.scaled(
                    200, 200, 
                    Qt.KeepAspectRatio, 
                    Qt.SmoothTransformation
                )
            
            self.preview_label.setPixmap(pixmap)
            
            # 显示图像信息
            self.preview_label.setToolTip(
                f"名称: {self.current_image}\n"
                f"大小: {img_info['Width']} x {img_info['Height']}\n"
                f"位置: ({img_info['XPos']}, {img_info['YPos']})\n"
                f"偏移: ({img_info['XOffset']}, {img_info['YOffset']})"
            )
        except Exception as e:
            print(f"预览图像出错: {e}")
            # 出错时显示占位符
            pixmap = QPixmap(200, 200)
            pixmap.fill(QColor(200, 0, 0, 100))
            painter = QPainter(pixmap)
            painter.setPen(QColor(255, 255, 255))
            painter.drawText(pixmap.rect(), Qt.AlignCenter, f"图像加载失败: {e}")
            painter.end()
            self.preview_label.setPixmap(pixmap)
    
    def statusBar(self):
        """获取状态栏"""
        parent = self.parent()
        while parent:
            if hasattr(parent, 'statusBar'):
                return parent.statusBar()
            parent = parent.parent()
        return None 